package services;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import utils.HibernateUtil;
import common.Stock;

public class StockServices {
	
	// current values stored in the database.
	@SuppressWarnings("unchecked")
	public void getCurrentValues() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
        Session session = sessionFactory.openSession();  
        
		List<Stock> stocks = session.createQuery("from Stock").list();
		System.out.println("Current values are:\n");
		for(Stock stock: stocks)
			System.out.println(stock.toString());
		System.out.println("\n-----------------------------------------");
	}

	// saves a stock in the database if it doesn't exist
	@SuppressWarnings("unchecked")
	public void saveStock(Stock stock) {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
        Session session = sessionFactory.openSession();  
        Transaction tx = session.beginTransaction(); 
        
		List<Stock> stocks = session.createQuery("from Stock").list();
        if(stocks.indexOf(stock) > 0) {
        	System.out.println("Stock is alrady exists in the database.");
        	return;
        }
        
        for(Stock st : stocks) {
        	if (st.getStockId() == stock.getStockId()) {
        		System.out.println("Stock ID "+  stock.getStockId() + " is used");
        		return;
        	}
        }
        
        try {
        	session.save(stock);
        	tx.commit();
        	System.out.println(stock.toString() + " is saved.");
        } catch(Exception ex) {
        	tx.rollback();
        	throw new RuntimeException(ex + " ERROR : Rollbacked.");
        } finally {
        	session.close();
        }
	}
	
	// saves a list of stocks in the database if any of
	// them does not exist already
	@SuppressWarnings("unchecked")
	public void saveStocks(List<Stock> stocks) {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
        Session session = sessionFactory.openSession();  
        
        List<Stock> currentStocks = session.createQuery("from Stock").list();
        
        for(Stock stck : stocks) {
        	if(currentStocks.indexOf(stck) > 0)
        		continue;
        	else
        		saveStock(stck);
        }
	}
	
}
